/*
 *	Author: Vitaly Rozhkov
 *	vitaly.rozhkov@gmail.com
 *  http://bookvarius.livejournal.com
 *
*/

imageTypes = {
	SQUARE: 1,
	LANDSCAPE: 2,
	PORTRAIT: 3
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

String.prototype.isInteger = function() {
	return !this.match(/[^0-9]/);
}

function ConfigRead(fileName) {
	var settings = new Array();
	var line;
	var parsed_line;
	var file = new File(fileName);
	
	if(null == file || !file.open('r')){
		alert('Can\'t open config file to read \'' + file.fullName + '\'');
		return null;
	}
	while(!file.eof){
		line = file.readln();
		if(null != line){
			line = line.trim();
			if('' == line){
				continue;
			}
			
			if(line.match(/^#/)){
				//save comments
				settings[line] = '';
				continue;
			}
			var variable;
			var value;
			
			parsed_line = line.split('=');
			
			variable = parsed_line[0].trim();
			value = parsed_line[1].trim(); 
						
			settings[variable] = value;
		}
	}
	file.close();
	return settings;
}

function ConfigWrite(fileName, settings){
	var file = new File(fileName);
	var line;
	
	if(null == file || !file.open('w')){
		alert('Can\'t open config file to write \'' + file.fullName + '\'');
		return null;
	}
	
	for(var variable in settings){
		//restore comments
		if(variable.match(/^#/)){
			line = variable;
		}else{
			line = variable + ' = ' + settings[variable];
		}
		if(!file.writeln(line)){
			alert('Can\'t write option \'' + line + '\' to config file \'' + file.fullName + '\'');
			file.close();
			return -1;
		}
	}
	file.close();
	return 0;
}


function CheckDocument(silent) {
	if(null == silent){
		silent = 0;
	}
	
	if (!app.documents.length) {
		if(!silent){
			alert('There are no opened documents');
		}
		return -1;
	}
	return 0;
}

function getImgType(img){
	if(null == img){
		img = app.activeDocument;
	}	
	
	var type;
	if(img.width == img.height){
		type = imageTypes.SQUARE;
	} else if(img.width > img.height) {
		type = imageTypes.LANDSCAPE;
	} else {
		type = imageTypes.PORTRAIT;
	}
	return type;
}

function Exec(func){
	if(0 != CheckDocument()){
		return -1;
	}
	
	//save current settings
	var defaultRulerUnits = app.preferences.rulerUnits;
	app.preferences.rulerUnits = Units.PIXELS;
	
	func();
	
	//restore settings
	app.preferences.rulerUnits = defaultRulerUnits;
}
